package com.watson.webService.config;


import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.headers.Header;
import org.apache.cxf.helpers.DOMUtils;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.xml.namespace.QName;
import java.util.List;

/**
 * 客户端登录拦截器，设置认证信息,一般建在客户端
 *
 * @author: llun
 * @date: 2022/2/16 16:21
 * @version: 1.0
 */
public class ClientLoginInterceptor extends AbstractPhaseInterceptor<SoapMessage> {

    private final String username;
    private final String password;

    public ClientLoginInterceptor(String username, String password) {
        super(Phase.PRE_PROTOCOL);
        this.username = username;
        this.password = password;
        System.out.println("1111111111111111111111");
    }

    @Override
    public void handleMessage(SoapMessage message) throws Fault {
        List<Header> headers = message.getHeaders(); // 获取全部头信息
        Document document = DOMUtils.createDocument(); // 创建xml文档
        Element authElement = document.createElement("authority"); // 认证数据节点
        Element usernameElement = document.createElement("username");
        Element passwordElement = document.createElement("password");
        usernameElement.setTextContent(username);
        passwordElement.setTextContent(password);
        authElement.appendChild(usernameElement);
        authElement.appendChild(passwordElement);
        headers.add(0, new Header(new QName("authority"), authElement));
    }
}


